package me.stone.stanimeclient.page.setting

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.NavDirections
import androidx.navigation.fragment.findNavController
import com.mikepenz.aboutlibraries.Libs
import com.mikepenz.aboutlibraries.LibsBuilder
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.stone.stanimeclient.R
import me.stone.stanimeclient.base.AbsViewBindingFragment
import me.stone.stanimeclient.core.common.extensions.launchAndRepeatWithLifecycle
import me.stone.stanimeclient.databinding.FragmentSettingsBinding
import timber.log.Timber

@AndroidEntryPoint
class SettingFragment : AbsViewBindingFragment<FragmentSettingsBinding>() {

    private val viewModel: SettingViewModel by viewModels()

    override fun buildViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentSettingsBinding {
        return FragmentSettingsBinding.inflate(
            inflater, container, false
        )
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        bindDataBinding {
            viewModel = this@SettingFragment.viewModel.apply {
                onAttachedToBinding()
            }
        }

        launchAndRepeatWithLifecycle {
            launch {
                viewModel.popDarkThemeSelectorDialogSign.collectLatest {
                    DarkThemeModeSelectDialog.newInstance()
                        .show(parentFragmentManager, null)
                }
            }

            launch {
                viewModel.darkThemeModeFlow.collect { mode ->
                    viewModel.updateDarkThemeSettingUI(mode)
                }
            }

            launch {
                viewModel.showLib.collectLatest {
                    showLibrariesFragment()
                }
            }
        }
    }

    private fun showLibrariesFragment() {
//        Timber.d("show libraries fragment ...")
//        val fragment = LibsBuilder().supportFragment()
//        parentFragmentManager.beginTransaction()
//            .add(fragment, "")
//            .show(fragment)
//            .commitNow()
        findNavController().navigate(object : NavDirections{
            override val actionId: Int
                get() = R.id.to_libraries

            override val arguments: Bundle
                get() = Bundle().apply {
                    putSerializable("data", LibsBuilder())
                }
        })
    }

}